<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :http-request="httpRequest"
  >
    <img v-if="imageUrl" v-show="!showProgress" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-show="showProgress" type="circle" :percentage="percent" class="progress" />
  </el-upload>
</template>

<script>

const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDGKCgy1o0yiCUXKr89uPgHdnjYHo8F8oG', // 身份识别ID
  SecretKey: 'OYUElCSVP7dxDQceUDk266tTqzueASYT' // 身份秘钥
})

export default {
  props: {
    src: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: this.src,
      percent: 0, // 上传进度
      showProgress: false // 是否展示进度条
    }
  },
  methods: {
    httpRequest(val) {
      this.showProgress = true
      this.imageUrl = URL.createObjectURL(val.file)
      console.log(val)
      if (val.file) {
        cos.putObject({
          Bucket: 'hhddw-85-1315592971',
          Region: 'ap-chengdu',
          Key: val.file.name,
          StorageClass: 'STANDARD',
          Body: val.file,
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          this.showProgress = false
          console.log(err || data)
          console.log(data)
          if (data.statusCode === 200) {
            // this.imageUrl = `https:${data.Location}`
            console.log(data.Location)
            this.$emit('update:src', `https:${data.Location}`)
          }
        })
      }
    }
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg'
    //   const isLt2M = file.size / 1024 / 1024 < 2

    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!')
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!')
    //   }
    //   return isJPG && isLt2M
    // }

  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  /* .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
} */
</style>

